import machine
from machine import ADC, Pin,I2C, deepsleep
from machine import RTC
import utime
import esp32
import DS3231
import IIC256
import sht31
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB)    # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v)
adc.width(ADC.WIDTH_12BIT)  
print(machine.wake_reason())
i2c = I2C(1, scl=Pin(18), sda=Pin(19), freq=400000)
wake1 = Pin(27, mode = Pin.IN,pull=machine.Pin.PULL_DOWN)
esp32.wake_on_ext0(pin = wake1, level = esp32.WAKEUP_ANY_HIGH)
# wake2 = Pin(27, mode = Pin.IN,pull=machine.Pin.PULL_DOWN)
# esp32.wake_on_ext1(pin = wake2, level = esp32.WAKEUP_ANY_HIGH)
rtc = RTC()


def callback1(str):
    print(str+"        ")
    IIC256.lprint(str,64,15)

def showFast():
    leds=machine.Pin(14,machine.Pin.IN,Pin.PULL_DOWN)
    showSlow()
    k=0
    for i in range(60):
        if(wake1.value()==1):
            k=k+1
            IIC256.lprint("%02d"%(k),64,15)
        else:
            k=0
            IIC256.lprint("               ",64,15)
        if k==3:

            DS3231.sync(callback1)
        da=i2c.readfrom_mem(104,0,1)
        s=((da[0]>>4) * 10) + (da[0]&0x0f)
        strs=("%02d"%(s))
        if(s==0): 
            showSlow()
        IIC256.lprint(strs,28,1)
        t=rtc.datetime()
        print(i)
        if i%2 == 0 :gett()
        utime.sleep_us(1000000-t[7])


        
    IIC256.lprint("       ",27,1)
    leds=machine.Pin(14,machine.Pin.IN,Pin.PULL_UP)
    machine.deepsleep((60-s)*1000)
    # machine.deepsleep(5000)

def showSlow():
    da=i2c.readfrom_mem(104,0,7)
    s=((da[0]>>4) * 10) + (da[0]&0x0f)
    m1=da[1]>>4
    m2=da[1]&0x0f
    h1=da[2]>>4
    h2=da[2]&0x0f
    t1=[h1,h2,10,m1,m2]
    d=((da[4]>>4) * 10) + (da[4]&0x0f)
    w=((da[3]>>4) * 10) + (da[3]&0x0f)
    mo=((da[5]>>4) * 10) + (da[5]&0x0f)
    y=((da[6]>>4) * 10) + (da[6]&0x0f)
    IIC256.lprint("20%02d-%02d-%02d"%(y,mo,d),28,2)
    IIC256.lcdAddress(170,4,16,16)
    IIC256.LDS(xj[7])
    IIC256.lcdAddress(170+16,4,16,16)
    IIC256.LDS(xj[8])
    IIC256.lcdAddress(170+32,4,16,16)
    IIC256.LDS(xj[w])

    gett()
    n=0
    for t in t1:
        IIC256.lcdAddress(n*32,0,32,64)
        for i in range(16):
            IIC256.LDS(IIC256.bigzf[t*16+i])
        n=n+1
def gett():
    sht31.sht31m(i2c)
    utime.sleep_ms(30)
    (shtrt,shtrh)=sht31.sht31r(i2c)
    IIC256.print32("%.2fC %.2f%%   "%(shtrt,shtrh),0,8)
    v=adc.read()

    IIC256.lprint("%.2fV  %d "%(v*7.73/4096,v),0,12)

if machine.wake_reason() == 0:


    IIC256.LCDInit()
    print("poweron")
    # PFC8563.sync()
    showFast()

if machine.wake_reason() == 2:
    print("key")
    showFast()
if machine.wake_reason() == 4:
    showSlow()
    da=i2c.readfrom_mem(104,0,1)
    s=((da[0]>>4) * 10) + (da[0]&0x0f)
    print("timer")
    machine.deepsleep((60-s)*1000)
    # machine.deepsleep(5000)
       



